﻿using Client.Constant;
using Client.Framework.Message;
using Client.Model;
using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Navigation;

namespace Client.Message.Response
{
    [MessageAttr(MessageId.RESPONSE_MENUS_TREE)]
    class MenusTreeResp : ResponseBaseMessage
    {

        public List<MainMenu> MainMenus { get; private set; }

        public int IsAll { get; set; }

        private readonly Dictionary<int, MainMenu> mainMenusDic = new Dictionary<int, MainMenu>();

        public override void Deserialize(byte[] buffer)
        {
            ResponseMenusTree msg = ResponseMenusTree.Parser.ParseFrom(buffer);
            IsAll = msg.IsAll;
            GetMainMenus(msg.Menus.ToList());
        }



        private void GetMainMenus(List<Menu> menus)
        {
            MainMenus = menus.FindAll(menu =>
            {
                return menu.ParentId == 0;
            }).Select(m =>
            {
                MainMenu mm = new MainMenu()
                {
                    ID = m.Id,
                    Name = m.MenuName,
                    Icon = m.Icon,
                    Screen = m.ScreenCode
                };
                if (m.CheckedType == 1)
                {
                    mm.Checked = true;
                }
                else if (m.CheckedType == 2)
                {
                    mm.Checked = false;
                }
                else if (m.CheckedType == 3)
                {
                    mm.Checked = null;
                }
                mainMenusDic.Add(m.Id, mm);
                return mm;
            }).ToList();
            // 将子菜单添加到主菜单中
            AddSubMenus(menus);
        }


        private void AddSubMenus(List<Menu> menus)
        {
            menus.FindAll(menu =>
            {
                return menu.ParentId != 0;
            }).Select(m =>
            {
                SubMenu sm = new SubMenu()
                {
                    ID = m.Id,
                    Name = m.MenuName,
                    Icon = m.Icon,
                    Screen = m.ScreenCode,
                    ParentId = m.ParentId,
                };
                if (m.CheckedType == 1)
                {
                    sm.Checked = true;
                }
                else if (m.CheckedType == 2)
                {
                    sm.Checked = false;
                }
                return sm;
            }).ToList().ForEach(sm =>
            {
                if (mainMenusDic.ContainsKey(sm.ParentId))
                {
                    MainMenu parent = mainMenusDic[sm.ParentId];
                    parent.SubMenus.Add(sm);
                    sm.Parent = parent;
                }
            });
        }



    }
}
